package cn.admin.remoting.impl;

import cn.admin.remoting.Client;
import cn.admin.remoting.Connection;
import cn.admin.remoting.IOEventListener;
import cn.admin.remoting.Remoting;
import cn.admin.remoting.locale.LogResources;
import cn.admin.remoting.util.ConnectionUrl;
import cn.admin.remoting.util.LoggerInit;

public class CL_IdleListener implements IOEventListener.ConnectionIdleListener {


    @Override
    public void connectionIdle(Connection connection) {

        long current = System.currentTimeMillis();
        long lastRead = ((DefaultConnection)connection).getIoSession().getLastReadTime();
        long idleTime = 0L;
        long maxReadIdle = 30000L;
        String url = connection.isClientSide() ? connection.getClient().getConnectionUrl() :
                HeartBeatProcessor.clientTargetUrl(connection);
        if (url != null) {
            idleTime = (long)ConnectionUrl.getIdleTimeout(url) * 1000L;
            maxReadIdle = (long)ConnectionUrl.getMaxReadIdle(url) * 1000L;
        }

        boolean isIdleTimeout = current - lastRead >= idleTime + maxReadIdle;

        if (isIdleTimeout && Remoting.isCloseWhenIdleTimeout()) {
            String msg = null;

            try {
                String label = connection.isClientSide() ? "clientExceedsMaxReadIdle" : "serverExceedsMaxReadIdle";
                msg = LogResources.getLog(label,(current - lastRead) / 1000);
            } finally {
                connection.close(msg);
            }
        } else if (connection.isClientSide()) {
            Client client = connection.getClient();
            ConnectionHeartBeat hb = new ConnectionHeartBeat(client.getConnectionUrl());
            client.invokeWithFuture(hb,null);
            LoggerInit.LOGGER.debug("[heart-beat] To " + connection.getRemoteSocket());
        }
    }
}
